package com.mezz.bones.framework.mybatis.dynamic.config;

import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import com.mezz.bones.framework.mybatis.dynamic.domain.dto.DynamicDataSourceInfo;
import com.mezz.bones.framework.mybatis.dynamic.enhance.EnhancedDynamicRoutingDataSource;
import com.mezz.bones.framework.mybatis.dynamic.provider.DataSourceInfoProvider;
import com.mezz.bones.framework.mybatis.dynamic.service.DataSourceCreatorService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.sql.DataSource;
import java.util.List;

@Configuration
@EnableTransactionManagement
@AllArgsConstructor
@Slf4j
public class DynamicDataSourceConfig implements CommandLineRunner {

    private final DataSource dataSource;
    private final DataSourceInfoProvider dataSourceInfoProvider;
    private final DynamicDataSourceProperties dataSourceProperties;
    private final DataSourceCreatorService dataSourceCreatorService;

    @Override
    public void run(String... args) {

        EnhancedDynamicRoutingDataSource ds = (EnhancedDynamicRoutingDataSource) dataSource;

        // 动态加载多数据源配置
        List<DynamicDataSourceInfo> dataSourceInfos = dataSourceInfoProvider.loadAllDataSourceInfo();

        // 动态注册数据源
        for (DynamicDataSourceInfo dataSourceInfo : dataSourceInfos) {

            ds.addDataSource(dataSourceInfo.getDatasourceKey(),
                    dataSourceCreatorService.createDatasource(dataSourceInfo)
            );

        }

    }
}